import { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
import { GroupService } from '../services/GroupService';
import { CreateGroupRequest, UpdateGroupRequest } from '../types/group';

// 请求参数类型定义
interface GroupIdParams {
  id: string;
}

interface ReorderGroupsBody {
  groupOrders: { id: string; order: number }[];
}

export async function groupRoutes(fastify: FastifyInstance) {
  // 获取所有分组
  fastify.get('/', {
    schema: {
      description: '获取所有分组列表',
      tags: ['分组管理'],
      response: {
        200: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            message: { type: 'string' },
            data: {
              type: 'array',
              items: {
                type: 'object',
                properties: {
                  id: { type: 'string' },
                  name: { type: 'string' },
                  description: { type: 'string' },
                  icon: { type: 'string' },
                  color: { type: 'string' },
                  order: { type: 'number' },
                  createdAt: { type: 'string' },
                  updatedAt: { type: 'string' }
                }
              }
            }
          }
        }
      }
    }
  }, async (request: FastifyRequest, reply: FastifyReply) => {
    const result = await GroupService.getAllGroups();
    return reply.code(result.success ? 200 : 400).send(result);
  });

  // 获取所有分组及其网站
  fastify.get('/with-websites', {
    schema: {
      description: '获取所有分组及其包含的网站',
      tags: ['分组管理'],
      response: {
        200: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            message: { type: 'string' },
            data: {
              type: 'array',
              items: {
                type: 'object',
                properties: {
                  id: { type: 'string' },
                  name: { type: 'string' },
                  description: { type: 'string' },
                  icon: { type: 'string' },
                  color: { type: 'string' },
                  order: { type: 'number' },
                  createdAt: { type: 'string' },
                  updatedAt: { type: 'string' },
                  websites: {
                    type: 'array',
                    items: {
                      type: 'object',
                      properties: {
                        id: { type: 'string' },
                        name: { type: 'string' },
                        description: { type: 'string' },
                        url: { type: 'string' },
                        logo: { type: 'string' },
                        groupId: { type: 'string' },
                        order: { type: 'number' },
                        isActive: { type: 'boolean' },
                        createdAt: { type: 'string' },
                        updatedAt: { type: 'string' }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }, async (request: FastifyRequest, reply: FastifyReply) => {
    const result = await GroupService.getAllGroupsWithWebsites();
    return reply.code(result.success ? 200 : 400).send(result);
  });

  // 获取分组详情
  fastify.get('/:id', {
    schema: {
      description: '获取分组详情（包含网站列表）',
      tags: ['分组管理'],
      params: {
        type: 'object',
        properties: {
          id: { type: 'string', description: '分组ID' }
        },
        required: ['id']
      },
      response: {
        200: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            message: { type: 'string' },
            data: {
              type: 'object',
              properties: {
                id: { type: 'string' },
                name: { type: 'string' },
                description: { type: 'string' },
                icon: { type: 'string' },
                color: { type: 'string' },
                order: { type: 'number' },
                createdAt: { type: 'string' },
                updatedAt: { type: 'string' },
                websites: {
                  type: 'array',
                  items: {
                    type: 'object',
                    properties: {
                      id: { type: 'string' },
                      name: { type: 'string' },
                      description: { type: 'string' },
                      url: { type: 'string' },
                      logo: { type: 'string' },
                      groupId: { type: 'string' },
                      order: { type: 'number' },
                      isActive: { type: 'boolean' },
                      createdAt: { type: 'string' },
                      updatedAt: { type: 'string' }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }, async (request: FastifyRequest<{ Params: GroupIdParams }>, reply: FastifyReply) => {
    const { id } = request.params;
    const result = await GroupService.getGroupById(id);
    return reply.code(result.success ? 200 : 404).send(result);
  });

  // 创建新分组
  fastify.post('/', {
    schema: {
      description: '创建新分组',
      tags: ['分组管理'],
      body: {
        type: 'object',
        properties: {
          name: { type: 'string', description: '分组名称' },
          description: { type: 'string', description: '分组描述' },
          icon: { type: 'string', description: '分组图标' },
          color: { type: 'string', description: '分组颜色' },
          order: { type: 'number', description: '排序顺序' }
        },
        required: ['name']
      },
      response: {
        201: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            message: { type: 'string' },
            data: {
              type: 'object',
              properties: {
                id: { type: 'string' },
                name: { type: 'string' },
                description: { type: 'string' },
                icon: { type: 'string' },
                color: { type: 'string' },
                order: { type: 'number' },
                createdAt: { type: 'string' },
                updatedAt: { type: 'string' }
              }
            }
          }
        }
      }
    }
  }, async (request: FastifyRequest<{ Body: CreateGroupRequest }>, reply: FastifyReply) => {
    const result = await GroupService.createGroup(request.body);
    return reply.code(result.success ? 201 : 400).send(result);
  });

  // 更新分组
  fastify.put('/:id', {
    schema: {
      description: '更新分组信息',
      tags: ['分组管理'],
      params: {
        type: 'object',
        properties: {
          id: { type: 'string', description: '分组ID' }
        },
        required: ['id']
      },
      body: {
        type: 'object',
        properties: {
          name: { type: 'string', description: '分组名称' },
          description: { type: 'string', description: '分组描述' },
          icon: { type: 'string', description: '分组图标' },
          color: { type: 'string', description: '分组颜色' },
          order: { type: 'number', description: '排序顺序' }
        }
      },
      response: {
        200: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            message: { type: 'string' },
            data: {
              type: 'object',
              properties: {
                id: { type: 'string' },
                name: { type: 'string' },
                description: { type: 'string' },
                icon: { type: 'string' },
                color: { type: 'string' },
                order: { type: 'number' },
                createdAt: { type: 'string' },
                updatedAt: { type: 'string' }
              }
            }
          }
        }
      }
    }
  }, async (request: FastifyRequest<{ Params: GroupIdParams; Body: UpdateGroupRequest }>, reply: FastifyReply) => {
    const { id } = request.params;
    const result = await GroupService.updateGroup(id, request.body);
    return reply.code(result.success ? 200 : 400).send(result);
  });

  // 删除分组
  fastify.delete('/:id', {
    schema: {
      description: '删除分组（分组下不能有网站）',
      tags: ['分组管理'],
      params: {
        type: 'object',
        properties: {
          id: { type: 'string', description: '分组ID' }
        },
        required: ['id']
      },
      response: {
        200: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            message: { type: 'string' }
          }
        }
      }
    }
  }, async (request: FastifyRequest<{ Params: GroupIdParams }>, reply: FastifyReply) => {
    const { id } = request.params;
    const result = await GroupService.deleteGroup(id);
    return reply.code(result.success ? 200 : 400).send(result);
  });

  // 强制删除分组（同时删除分组下的所有网站）
  fastify.delete('/:id/force', {
    schema: {
      description: '强制删除分组（同时删除分组下的所有网站）',
      tags: ['分组管理'],
      params: {
        type: 'object',
        properties: {
          id: { type: 'string', description: '分组ID' }
        },
        required: ['id']
      },
      response: {
        200: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            message: { type: 'string' },
            data: {
              type: 'object',
              properties: {
                deletedWebsites: { type: 'number' }
              }
            }
          }
        }
      }
    }
  }, async (request: FastifyRequest<{ Params: GroupIdParams }>, reply: FastifyReply) => {
    const { id } = request.params;
    const result = await GroupService.forceDeleteGroup(id);
    return reply.code(result.success ? 200 : 400).send(result);
  });

  // 重新排序分组
  fastify.put('/reorder', {
    schema: {
      description: '重新排序分组',
      tags: ['分组管理'],
      body: {
        type: 'object',
        properties: {
          groupOrders: {
            type: 'array',
            items: {
              type: 'object',
              properties: {
                id: { type: 'string', description: '分组ID' },
                order: { type: 'number', description: '新的排序顺序' }
              },
              required: ['id', 'order']
            }
          }
        },
        required: ['groupOrders']
      },
      response: {
        200: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            message: { type: 'string' }
          }
        }
      }
    }
  }, async (request: FastifyRequest<{ Body: ReorderGroupsBody }>, reply: FastifyReply) => {
    const { groupOrders } = request.body;
    const result = await GroupService.reorderGroups(groupOrders);
    return reply.code(result.success ? 200 : 400).send(result);
  });
}